package net.starwifi.duobao.web;

import net.starwifi.duobao.entity.BaseEntity;
import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.oauth.Principal;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.RSAService;
import net.starwifi.duobao.utils.IpUtils;
import net.starwifi.duobao.utils.WebUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * Controller - 用户注册
 *
 * @author ruoo
 * @version 1.0
 */
@Controller("wapRegisterController")
public class RegisterController extends BaseController {

    @Autowired
    MemberService memberService;

    @Autowired
    RSAService rsaService;


    /**
     * 检查用户名是否被禁用或已存在
     */
    @RequestMapping(value = "/check_mobile", method = RequestMethod.GET)
    public @ResponseBody   boolean checkMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        Member member=memberService.findByMobile(mobile);
        if(member!=null){
            return false;
        }else {
            return true;
        }
    }


    /**
     * 检查用户名是否被禁用或已存在
     */
    @RequestMapping(value = "/check_username", method = RequestMethod.GET)
    public @ResponseBody boolean checkUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            return false;
        }
        if (memberService.usernameExists(username)) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 登录页面
     */
    @RequestMapping(value = "register",method = RequestMethod.GET)
    public String index(String redirectUrl, HttpServletRequest request, ModelMap model) {
        model.addAttribute("redirectUrl", redirectUrl);
        return "/register/register";
    }


    /**
     * 登录提交
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public @ResponseBody
    Object submit(String phone,String uuid,Integer sex,HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        if(sex==null){
            sex=0;
        }
        String uuidKey="sms_register_"+phone+"_"+"success";
        if(request.getSession().getAttribute(uuidKey)==null){
            return Message.error("无验证授权");
        }
        String sessionCode=(String)request.getSession().getAttribute(uuidKey);
        if(!sessionCode.equals(uuid)){
            return Message.error("无验证授权");
        }
        String password = rsaService.decryptParameter("pass", request);
        rsaService.removePrivateKey(request);
        if (!isValid(Member.class, "mobile", phone, BaseEntity.Save.class) || !isValid(Member.class, "password", password, BaseEntity.Save.class)) {
            return Message.error("参数格式错误");
        }
        if (password.length() < 6 || password.length() > 30) {
            return Message.error("密码长度错误");
        }
        if (memberService.findByMobile(phone)!=null) {
            return Message.error("手机号已经被注册");
        }
        final Member member = new Member();
        member.setUsername("m" + phone);
        String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
        member.setSalt(salt);
        member.setMobile(phone);
        member.setGender(sex);

        member.setPassword(DigestUtils.md5Hex(password + salt));

        member.setIsEnabled(true);
        member.setIsLocked(false);
        member.setLoginFailureCount(0);
        member.setLockedDate(null);
        member.setRegisterIp(IpUtils.getIpAddr(request));
        member.setLoginIp(IpUtils.getIpAddr(request));
        member.setLoginDate(new Date());
        member.setBalance(BigDecimal.ZERO);
        member.setCurrencyBalance(BigDecimal.ZERO);
        memberService.save(member);
        Map<String, Object> attributes = new HashMap<String, Object>();
        Enumeration<?> keys = session.getAttributeNames();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            attributes.put(key, session.getAttribute(key));
        }
        session.invalidate();
        session = request.getSession();
        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            session.setAttribute(entry.getKey(), entry.getValue());
        }
        String userAgent=request.getHeader("User-Agent");
        String cookiePass=DigestUtils.md5Hex(userAgent + member.getPassword());
        session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername()));
        WebUtils.addCookie(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
        WebUtils.addCookie(request, response, Member.COOKIE_PASS_NAME, cookiePass);
        return Message.createMessage(Message.success("登陆成功"), new HashMap<String, Object>() {{
            put("entity", member);
        }});
    }

}
